#include <bits/stdc++.h>
#include <unistd.h>
#include "rs485.h"
using namespace std;

#define THREAD_NUM	(50)

void _thread_task(int num);

int main() {
    auto ModBus485_Instance = RS485_Handler::GetInstance();
    ModBus485_Instance->init("/dev/ttyUSB0",115200, true, false);
    vector<thread*> thread_test(THREAD_NUM, nullptr);
    // vector<uint16_t> data_buf1(10);
    // vector<uint16_t> data_buf2(10);
    // vector<uint16_t> data_buf3(10);

    // while (1)
    // {
    //     ModBus485_Instance->ReadInputRegister(2, data_buf1, 1, 2);
    //     for(int i=0;i<2;++i) {
    //         cout << data_buf1[i] << '\t';
    //     }
    //     cout << endl;

    //     data_buf2[0] = data_buf2[1];
    //     data_buf2[1] = data_buf2[0] + 1;
    //     ModBus485_Instance->WriteHoldingRegister(2, data_buf2, 1, 2);
    //     ModBus485_Instance->ReadHoldingRegister(2, data_buf3, 1, 2);
    //     for(int i=0;i<2;++i) {
    //         cout << data_buf3[i] << '\t';
    //     }
    //     cout << endl;
    //     sleep(1);
    // }
    for(int i=0;i<THREAD_NUM;++i) {
        thread_test[i] = new thread(_thread_task, i%5 + 1);
    }
    for(int i=0;i<THREAD_NUM;++i) {
        thread_test[i]->join();
    }
    for(int i=0;i<THREAD_NUM;++i) {
        delete thread_test[i];
        thread_test[i] = nullptr;
    }
    
    return 0;
}

void _thread_task(int num)
{
    auto ModBus485_Instance = RS485_Handler::GetInstance();
    vector<uint16_t> data_buf1(10);
    vector<uint16_t> data_buf2(10);
    vector<uint16_t> data_buf3(10);
    for(int i=1;i<num+30;++i) {
        ModBus485_Instance->ReadInputRegister(i % 5 + 1, data_buf1, 1, 2);
        for(int i=0;i<2;++i) {
            cout << data_buf1[i] << '\t';
        }
        cout << endl;
        data_buf2[0] = data_buf2[1];
        data_buf2[1] = data_buf2[0] + 1;
        ModBus485_Instance->WriteHoldingRegister(i % 5 + 1, data_buf2, 1, 2);
        ModBus485_Instance->ReadHoldingRegister(i % 5 + 1, data_buf3, 1, 2);
        for(int i=0;i<2;++i) {
            cout << data_buf3[i] << '\t';
        }
        cout << endl;
        sleep(i % 3 + 1);
    }
}
